#include "RingQueue.hpp"
#include "task.hpp"
#include <ctime>
#include <pthread.h>
#include <memory>
#include <sys/types.h>
#include <unistd.h>
#include <cstring>


using namespace std;

const char *ops = "+-*/%";

void* consumerRoutine(void* args){
    RingQueue<Task> *rq = static_cast<RingQueue<Task> *>(args);

    while(1){
        Task t;
        //把任务从共享区拷贝到私有上下文
        rq->pop(&t);
        //仿函数处理任务
        t();
        cout << "consumer: " << t.formatArg() << t.formatRes() << endl;
    }
}

void* productorRoutine(void* args){
    RingQueue<Task> *rq = static_cast<RingQueue<Task> *>(args);
    
    while(1){
        int x = rand() % 100 + 1;
        int y = rand() % 100 + 1;
        char op = ops[rand() % strlen(ops)];
        Task t(x, y, op);
        rq->push(t);
        cout << "productor: " << t.formatArg() << endl;
        
    }
}

// //单生产单消费
// int main(){

//     srand(time(nullptr) ^ getpid());

//     RingQueue<Task> *rq = new RingQueue<Task>();

//     pthread_t c, p;
//     pthread_create(&c, nullptr, consumerRoutine, rq);
//     pthread_create(&p, nullptr, productorRoutine, rq);

//     pthread_join(c, nullptr);
//     pthread_join(p, nullptr);

//     delete rq;

//     return 0;
// }


//多生产多消费
int main(){
    
    srand(time(nullptr) ^ getpid());
    RingQueue<Task> *rq = new RingQueue<Task>();

    pthread_t c[3], p[2];
    for (int i = 0; i < 3;i++){
        pthread_create(&c[i], nullptr, consumerRoutine, rq);
    }

    for (int i = 0; i < 2;i++){
        pthread_create(&p[i], nullptr, productorRoutine, rq);
    }

    for (int i = 0; i < 3;i++){
        pthread_join(c[i], nullptr);
    }

    for (int i = 0; i < 2;i++){
        pthread_join(p[i], nullptr);
    }

    return 0;
}